<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Realtime_data extends MY_Controller {

	function Realtime_data() {
		parent::__construct();
		$this->load->model('realtime_data_model');
		$this->load->model('realtime_item_model');
	}

	public function index() {
		$realtime_data = $this->realtime_data_model->get_data_list();
		$datas = array();
		if(empty($realtime_data)) {
			$datas[] = array('item_name' => 'none data','data_value' => 'none data', 'data_time' => 'none data', 'data_server' => 'none data');
		} else {
			foreach($realtime_data as $row) {
				$item_id = $row['item_id'];
				$data_value = $row['data_value'];
				$data_time = $row['data_time'];
				$data_server = $row['data_server'];
				$item_ids = $this->realtime_item_model->get_by_id($item_id);
				$item_name = $item_ids['item_name'];
				$data = array('item_name' => $item_name, 'data_value' => $data_value, 'data_time' => $data_time, 'data_server' => $data_server);
				array_push($datas, $data);
			} 
		}
		if($this->session->userdata('logged_in')){
			$this->load->view('realtime_data', array('datas' => $datas));
		} else {
			$this->load->view('login');
		}
	}

	public function add() {
		$from_ip = $this->input->ip_address();
		switch ($from_ip)
		{
		case "120.24.166.15":
		  $data_server = "sz";
		  break;
		case "52.68.67.135":
		  $data_server = "jp";
		  break;
		case "58.96.171.124":
		  $data_server = "hk";
		  break;
		default:
		  $data_server = "none";
		}
		$salt        = "slightech"; 
		$token_fetch = $this->input->post('token');
		$item_key    = $this->input->post('item_key');
		$item_info   = $this->realtime_item_model->get_by_key_server($item_key,$data_server);
		$item_id     = $item_info['item_id'];
		$data_value  = $this->input->post('data_value');
		$data_time   = time();
		$data_date   = date('Y-m-d');
		$token       = md5($salt.$item_key.$data_value.$data_date);
		if( $token == $token_fetch ) {
			if( $data_value >= $item_info['alarm_value'] ) { 
				$this->load->library('mailer');
				$this->mailer->sendmail("timfan@slightech.com", "Alarm from server ".$item_info['item_server']." (".date("Y-m-d H:i:s",$data_time).")", $item_info['alarm_content']);
				$this->realtime_data_model->add_alarm($item_info['alarm_content'], $data_time);
			}
			$this->realtime_data_model->add($item_id, $data_value, $data_time, $data_server);
		}
	}

	public function get_realtime_data() { 
		$item_id     = $this->input->get('item_id');
		$item_server = $this->input->get('item_server');
		$latest_data = $this->realtime_data_model->get_latest_data($item_id);
		echo json_encode($latest_data);
	}

	public function check_and_alarm() { 
		$alarm_info = $this->realtime_data_model->check_alarm();
		echo json_encode($alarm_info);
	}

	public function solve_alarm() { 
		$alarm_id = $this->input->post("alarm_id");
		$this->realtime_data_model->solve_alarm($alarm_id);
		redirect("/report");
	}
	
}